package com.peanut.baby;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import com.peanut.baby.config.ConfigParamsManager;
import com.peanut.baby.http.ApiException;
import com.peanut.baby.http.BaseObserver;
import com.peanut.baby.http.BaseResponse;
import com.peanut.baby.http.BaseScheduler;
import com.peanut.baby.http.RetrofitClient;
import com.peanut.baby.model.PTag;
import com.peanut.baby.model.User;
import com.peanut.baby.repository.UserRepository;
import com.peanut.baby.util.DevicesUtils;
import com.peanut.baby.util.ShareUtil;
import com.peanut.devlibrary.LibContext;
import com.peanut.devlibrary.LibInitManager;
import com.peanut.devlibrary.imageloader.ImageLoader;
import com.peanut.devlibrary.util.DeviceInfo;
import com.peanut.devlibrary.util.SmsUtil;
import com.peanut.devlibrary.util.StringUtil;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.mars.xlog.Log;

import java.io.File;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by anonymouslystudio on 2017/6/13.
 */

public class InitManager {
    private static final String TAG = InitManager.class.getSimpleName();
    private Context ctx;
    private User    user;
    private List<PTag> tags;
    private int     screenWidth=0;
    private int     screenHeight=0;
    public DeviceInfo  info;
    public String   pushId;
    public long playingId;
    public int unreadCount = 0;

    private int counter = 0;
    Timer timer;
    TimerTask counterTask;
    private InitManager(){}

    public List<String> getSearchKeywords() {
        return searchKeywords;
    }

    public void setSearchKeywords(List<String> searchKeywords) {
        this.searchKeywords = searchKeywords;
    }

    private List<String> searchKeywords;

    /**
     *
     */
    private static class InstanceHolder{
        private static final InitManager instance = new InitManager();
    }

    /**
     *
     * @return
     */
    public static InitManager getInstance(){
        return InstanceHolder.instance;
    }

    public String getUserId(){
        if(getUser() == null){
            return "";
        }
        return getUser().userId;
    }
    public String getUserToken(){
        if(getUser() == null){
            return "";
        }
        return getUser().userToken;
    }
    public String getUserIdOrZero(){
        if(getUser() == null){
            return "0";
        }
        return getUser().userId;
    }

    public void init(Context ctx){
        LibInitManager.getInstance().setDebug(BuildConfig.DEBUG);
        LibInitManager.getInstance().setLogDir(AppConfig.CacheConfig.APP_LOG_DIR);
        LibInitManager.getInstance().init(ctx);
        if(!LeakCanary.isInAnalyzerProcess(ctx)){
            this.ctx = ctx;
            checkDirs();
            ShareUtil.getInstance().init(ctx);
            SmsUtil.getInstance().init(ctx);

            LibContext.getInstance().init(ctx);
            DevicesUtils.initDevicesInfos();
            ImageLoader.getInstance().setDefaultImageId(R.drawable.icon_default_logo);
            ConfigParamsManager.getInstance().updateAllConfigs();
        }
        getSearchKeyWords();
        startCounter();
    }

    private void startCounter(){
        counter = 0;
        timer = new Timer();
        counterTask = new TimerTask() {
            @Override
            public void run() {
                counter ++;
            }
        };
       timer.schedule(counterTask,1000);
    }

    public int getCounter(){
        return counter;
    }

    public void stopCounter(){
        if(counterTask != null){
            counterTask.cancel();
            counterTask = null;
        }
        if(timer != null){
            timer.cancel();
            timer = null;
        }
    }



    public int getScreenWidth(){
        if(screenWidth == 0){
            screenWidth = ctx.getResources().getDisplayMetrics().widthPixels;
        }
        return screenWidth;
    }
    public int getScreenHeight(){
        if(screenHeight == 0){
            screenHeight = ctx.getResources().getDisplayMetrics().heightPixels;
        }
        return screenHeight;
    }

    public void checkDirs(){
        File f = new File(AppConfig.CacheConfig.APP_IMAGE_DIR);
        File f1 = new File(AppConfig.CacheConfig.APP_LOG_DIR);
        File f2 = new File(AppConfig.CacheConfig.APP_VOICE_DIR);
        if(!f.exists() || !f.isDirectory()){
            f.delete();
            f.mkdirs();
        }
        if(!f1.exists() || !f1.isDirectory()){
            f1.delete();
            f1.mkdirs();
        }
        if(!f2.exists() || !f2.isDirectory()){
            f2.delete();
            f2.mkdirs();
        }
    }

    public String getCacheImagePath(String fileName){
        return AppConfig.CacheConfig.APP_IMAGE_DIR + fileName;
    }

    public String getImageCacheDir(){
        return AppConfig.CacheConfig.APP_IMAGE_DIR;
    }

    public String getVoiceDir(){
        return AppConfig.CacheConfig.APP_VOICE_DIR;
    }

    public User getUser(){
        if(user == null){
            user = UserRepository.getInstance().getCurrentUser();
        }
        return user;
    }

    public void setUser(User user){
        this.user = user;
        UserRepository.getInstance().updateCurrentUser(user);

    }

    public List<PTag> getTags(){
        if(tags == null){
            tags = UserRepository.getInstance().getTags();
        }
        return tags;
    }

    public void setTags(List<PTag> tags){
        this.tags = tags;
        UserRepository.getInstance().updateTags(tags);

    }

    public void updateLocalUser(){
       UserRepository.getInstance().updateCurrentUser(user);

    }

    public Context getCtx(){
        return ctx;
    }

    public void onApiError(String errorCode){
        Log.d(TAG,"onApiError: "+errorCode);
        if(errorCode.equals(ApiException.ERROR_TOKEN_EXPRIED)){
            ctx.sendBroadcast(new Intent(AppConfig.BroadCastConfig.ACTION_TOKEN_EXPIRES));
        }else if(errorCode.equals(ApiException.ERROR_LACK_OF_POINT)){
            ctx.sendBroadcast(new Intent(AppConfig.BroadCastConfig.ACTION_LACK_POINT));
        }else if(errorCode.equals(ApiException.ERROR_NEED_TOKEN)){
            ctx.sendBroadcast(new Intent(AppConfig.BroadCastConfig.ACTION_NEED_TOKEN));
        }else if(errorCode.equals(ApiException.ERROR_NETWORK_FAILED)){
            ctx.sendBroadcast(new Intent(AppConfig.BroadCastConfig.ACTION_NETWORK_FAILED));
        }

    }

    public void uploadPushIdIfNeeded(){
        if(InitManager.getInstance().getUser() != null
                && !StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)
                && !StringUtil.isNullOrEmpty(pushId)){
            RetrofitClient.getInstance().uploadPushToken(InitManager.getInstance().getUser().userToken,
                    InitManager.getInstance().getUserId(),1,pushId).compose(BaseScheduler.<BaseResponse<String>>compose()).subscribe(new BaseObserver<String>() {
                @Override
                protected void onHandleSuccess(String s) {
//                    Log.d(TAG,"AAA");
//                    PushManager.getInstance().setTag(ctx, TestUtils.getTestPushTags(),"set tag");
                }

                @Override
                protected void onHandleError(String code,String msg) {

                }
            });
        }

    }

    public String getOneSearchKeyword(){
        if(searchKeywords == null ||  searchKeywords.isEmpty()){
            return "";
        }
        int index = new Random().nextInt(searchKeywords.size() - 1);
        return searchKeywords.get(index);
    }

    public void getSearchKeyWords(){
        RetrofitClient.getInstance().getHotTags(getUserId()).compose(BaseScheduler.<BaseResponse<List<String>>>compose()).subscribe(new BaseObserver<List<String>>() {
            @Override
            protected void onHandleSuccess(List<String> s) {
                searchKeywords = s;
            }

            @Override
            protected void onHandleError(String code,String msg) {

            }
        });

    }

    public void resetPushBeforeLogout(){
        if(InitManager.getInstance().getUser() != null
                && !StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)){
            RetrofitClient.getInstance().uploadPushToken(InitManager.getInstance().getUser().userToken,
                    InitManager.getInstance().getUserId(),1,"").compose(BaseScheduler.<BaseResponse<String>>compose()).subscribe(new BaseObserver<String>() {
                @Override
                protected void onHandleSuccess(String s) {

                }

                @Override
                protected void onHandleError(String code,String msg) {

                }
            });
        }

    }

    public void logout(Activity act){
        //clear user info
        resetPushBeforeLogout();
        InitManager.getInstance().setUser(null);
        //log as unlogged
        Intent i = act.getPackageManager()
                .getLaunchIntentForPackage(act.getPackageName());
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        act.startActivity(i);
        act.finish();
    }
}
